<template>
    <div class="flex flex-col h-full w-full overflow-hidden">
        <div class="tool-bar">
            <div class="flex mb-1">
                <ElInput
                    v-model="inputingUrl"
                    placeholder="请输入网址"
                    class="w-full mr-1"
                    @keypress.enter="goTo(inputingUrl)"
                ></ElInput>
                <!-- <ElCheckbox v-model="explorerConfig.isPhone">移动端</ElCheckbox> -->
                <ElButton @click="goTo(inputingUrl)">前往</ElButton>
                <!-- touch mode -->
                <div class="mr-1">
                    <el-switch
                        v-model="explorerConfig.isTouchMode"
                        class="ml-2"
                        width="60"
                        inline-prompt
                        active-text="touch"
                        inactive-text="pointer"
                        @change="toggleTouchMode"
                    />
                </div>
                <!-- mobile mode -->
                <div class="mr-1">
                    <el-switch
                        v-model="explorerConfig.isMobile"
                        class="ml-2"
                        width="60"
                        inline-prompt
                        active-text="mobile"
                        inactive-text="pc"
                        @change="toggleMobileMode"
                    />
                </div>
                <ElButton @click="toggleDevtools"
                    >{{ explorerConfig.devtoolsOpened ? '关闭' : '打开' }}开发者工具</ElButton
                >
            </div>
        </div>
        <div class="content w-full h-full">
            <!-- <div class="web-content-view w-full h-full" ref="webContentViewRef"></div> -->
            <el-splitter @resize="handleSplitterResize">
                <el-splitter-panel :min="100">
                    <div class="flex flex-col h-full w-full">
                        <!-- <MobileParams @change="handleMobileParamsChange" /> -->
                        <div class="flex-1 w-full">
                            <webview ref="webviewRef" src="about: blank" class="w-full h-full"></webview>
                        </div>
                    </div>
                </el-splitter-panel>

                <el-splitter-panel :min="100" v-model:size="explorerConfig.devtoolParentWidth">
                    <webview ref="webviewDevtoolsRef" src="about: blank" class="w-full h-full"></webview>
                </el-splitter-panel>
            </el-splitter>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ElButton, ElInput } from 'element-plus'
import {
    getCurrentInstance,
    nextTick,
    onActivated,
    onDeactivated,
    onMounted,
    onUnmounted,
    reactive,
    ref,
    useTemplateRef
} from 'vue'
import './utils/installExtension'
import { WebviewContent } from './utils/webviewContent'

// 事件
const emit = defineEmits(['backgroundImageSelected', 'ready', 'urlChange'])
// 属性
const props = defineProps<{
    defaultUrl?: string
}>()
// 需要用到的变量
// const inputingUrl = ref('https://lanhuapp.com/')
// const inputingUrl = ref('https://lanhuapp.com/link/#/invite?sid=lx0gUnMS')
const inputingUrl = ref(props.defaultUrl || 'http://localhost:8080')
// 浏览器相关配置
const explorerConfig = reactive({
    // 是否移动端模式
    isMobile: false,
    // 是否触摸模式
    isTouchMode: false,
    // 开发者工具是否打开
    devtoolsOpened: false,
    // devtoolParentWidth
    devtoolParentWidth: '0'
})

// 保存webview的引用
const webviewRef = useTemplateRef<Electron.WebviewTag>('webviewRef')
const webviewDevtoolsRef = useTemplateRef<Electron.WebviewTag>('webviewDevtoolsRef')
// 浏览器实例
const webviewContent = new WebviewContent()

// 页面加载完成
onMounted(async () => {
    if (!webviewRef.value || !webviewDevtoolsRef.value) return
    await webviewContent.initBrowserContent({
        initialUrl: inputingUrl.value,
        webviewDom: webviewRef.value,
        webviewDevtoolsDom: webviewDevtoolsRef.value
    })
    // 注册事件
    registEventHandlers()
    // 触发准备好的事件
    emit('ready')
})

// 前往
const goTo = async (url: string) => {
    // 补全url
    if (!url.startsWith('http')) {
        url = 'http://' + url
    }

    inputingUrl.value = url

    webviewContent.loadUrl(url)

    // 触发urlChanged事件
    emit('urlChange', url)
    // webview.executeJavaScript(`window.location.href = '${url}';`)
}

// 打开开发者工具
const toggleDevtools = async () => {
    // 打开开发者工具
    webviewContent.webview?.openDevTools()
    if (explorerConfig.devtoolsOpened) {
        webviewContent.toggleDevtools(false)
        explorerConfig.devtoolsOpened = false
        explorerConfig.devtoolParentWidth = '0'
        return
    }
    webviewContent.toggleDevtools(true)
    explorerConfig.devtoolsOpened = true
    explorerConfig.devtoolParentWidth = '50%'
}
// 组件实例
const internal = getCurrentInstance()
// 注册事件
const registEventHandlers = () => {
    const webview = webviewContent.webview
    if (!webview) return
    // 导航事件
    webview.addEventListener('will-navigate', (e) => {
        inputingUrl.value = e.url
    })
    webview.addEventListener('did-navigate-in-page', (e) => {
        inputingUrl.value = e.url
    })

    const realProps = internal?.vnode?.props
    if (!realProps) return
    // 如果外部没有注册 background-image-selected事件，就不要监听
    if (typeof realProps?.onBackgroundImageSelected !== 'function') return
    // background-image-selected事件
    webviewContent.on('background-image-selected', (message) => {
        // ElMessage.info(message)
        // url("http://localhost:8081/@fs/Users/changba-cdos-068/changba/images/bg_act_header__link.png")
        // TODO: 获取图片路径，这里可能需要处理
        const filePath = message.split('@fs')[1]?.replace(`")`, '')
        if (!filePath) return
        emit('backgroundImageSelected', filePath)
    })
}

// 用splitter调整尺寸时
const handleSplitterResize = () => {
    webviewContent.handleContainerResize()
}
// 移动端参数发生变化
const toggleMobileMode = (value: boolean) => {
    webviewContent.toggleMobileMode(value)
}

// touch 模式发生变化
const toggleTouchMode = (value: boolean) => {
    webviewContent.toggleTouchMode(value)
}

onDeactivated(() => {
    webviewContent.setVisible(false)
})

onActivated(() => {
    webviewContent.setVisible(true)
    webviewContent.setVisible(explorerConfig.devtoolsOpened, 'devtools')
    nextTick(() => {
        // 手动触发window的resize事件
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'))
        }, 500)
    })
})
// 组件的可见性发生变化
onUnmounted(() => {
    webviewContent.destroy()
})

// 如果页面刷新也要销毁
window.addEventListener('beforeunload', () => {
    webviewContent.destroy()
})

// 往外暴露的方法
defineExpose({
    webviewContent
})
</script>

<style scoped></style>
